<template>
  <div class="app-container">
    <el-card class="questionnaire-card">
      <template #header>
        <div class="questionnaire-header">
          <h2>{{ questionnaire.title }}</h2>
          <p class="description">{{ questionnaire.description }}</p>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else class="questionnaire-content">
        <el-form 
          ref="answerFormRef" 
          :model="answerForm" 
          :rules="formRules" 
          label-width="0"
          class="questionnaire-form"
        >
          <div v-for="(question, index) in questions" :key="question.id" class="question-item">
            <div class="question-header">
              <span class="question-number">{{ index + 1 }}.</span>
              <span class="question-content">{{ question.content }}</span>
              <span v-if="question.required" class="required-mark">*</span>
            </div>
            
            <!-- 单选题 -->
            <div v-if="question.questionType === 'single'" class="question-options">
              <el-radio-group v-model="answerForm.answers[question.id]">
                <el-radio 
                  v-for="option in question.options" 
                  :key="option.id" 
                  :label="option.id"
                  class="option-item"
                >
                  {{ option.optionLabel }}
                </el-radio>
              </el-radio-group>
            </div>
            
            <!-- 多选题 -->
            <div v-else-if="question.questionType === 'multiple'" class="question-options">
              <el-checkbox-group v-model="answerForm.answers[question.id]">
                <el-checkbox 
                  v-for="option in question.options" 
                  :key="option.id" 
                  :label="option.id"
                  class="option-item"
                >
                  {{ option.optionLabel }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            
            <!-- 文本题 -->
            <div v-else-if="question.questionType === 'text'" class="question-text">
              <el-input 
                v-model="answerForm.answers[question.id]" 
                type="textarea" 
                :rows="3"
                placeholder="请输入您的答案"
                maxlength="500"
                show-word-limit
              />
            </div>
          </div>
          
          <div class="form-actions">
            <el-button type="primary" @click="submitAnswer" :loading="submitting">
              提交问卷
            </el-button>
            <el-button @click="saveDraft" :loading="saving">
              保存草稿
            </el-button>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup name="QnQuestionnaireFill">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getQuestionnaire, getQuestionList, listOptions, submitAnswer, submitAnswerWithDetails } from '@/api/questionnaire'
import useUserStore from '@/store/modules/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(true)
const submitting = ref(false)
const saving = ref(false)
const questionnaire = ref({})
const questions = ref([])
const answerFormRef = ref(null)

// 答卷表单数据
const answerForm = reactive({
  questionnaireId: null,
  submitterName: '',
  submitterEmail: '',
  submitterPhone: '',
  answers: {}
})

// 表单验证规则
const formRules = computed(() => {
  const rules = {}
  questions.value.forEach(question => {
    if (question.required) {
      rules[`answers.${question.id}`] = [
        { required: true, message: '此题是必填项', trigger: 'blur' }
      ]
    }
  })
  return rules
})

// 加载问卷数据
async function loadQuestionnaire() {
  const id = route.params.id
  try {
    // 获取问卷基本信息
    const questionnaireRes = await getQuestionnaire(id)
    questionnaire.value = questionnaireRes.data
    answerForm.questionnaireId = id
    
    // 获取题目列表
    const questionsRes = await getQuestionList(id)
    const questionList = questionsRes.rows || []
    
    // 为每个题目获取选项
    const questionsWithOptions = await Promise.all(
      questionList.map(async (question) => {
        if (question.questionType !== 'text') {
          try {
            const optionsRes = await listOptions(question.id)
            question.options = optionsRes.rows || []
          } catch (error) {
            console.error('获取题目选项失败:', error)
            question.options = []
          }
        } else {
          question.options = []
        }
        return question
      })
    )
    
    questions.value = questionsWithOptions
    
    // 初始化答案表单
    questions.value.forEach(question => {
      if (question.questionType === 'multiple') {
        answerForm.answers[question.id] = []
      } else {
        answerForm.answers[question.id] = ''
      }
    })
    
  } catch (error) {
    console.error('加载问卷失败:', error)
  } finally {
    loading.value = false
  }
}

// 提交问卷
async function submitAnswer() {
  try {
    await answerFormRef.value.validate()
    
    // 构建提交数据
    const submitData = {
      questionnaireId: answerForm.questionnaireId,
      userId: userStore.id || 1, // 从store获取用户ID，如果没有则使用默认值
      details: []
    }
    
    // 转换答案格式
    Object.keys(answerForm.answers).forEach(questionId => {
      const answer = answerForm.answers[questionId]
      if (answer && (Array.isArray(answer) ? answer.length > 0 : answer.trim())) {
        submitData.details.push({
          questionId: parseInt(questionId),
          optionValue: Array.isArray(answer) ? answer.join(',') : answer
        })
      }
    })
    
    submitting.value = true
    await submitAnswerWithDetails(submitData)
    ElMessage.success('问卷提交成功！')
    router.push('/questionnaire')
    
  } catch (error) {
    console.error('提交问卷失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 保存草稿
async function saveDraft() {
  saving.value = true
  try {
    // 这里可以实现草稿保存功能
    ElMessage.success('草稿保存成功')
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadQuestionnaire()
})
</script>

<style scoped>
.questionnaire-card {
  max-width: 800px;
  margin: 0 auto;
}

.questionnaire-header {
  text-align: center;
  margin-bottom: 20px;
}

.questionnaire-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.description {
  color: #606266;
  line-height: 1.6;
}

.loading-container {
  padding: 40px;
  text-align: center;
}

.questionnaire-form {
  padding: 20px 0;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
}

.question-header {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
}

.question-number {
  color: #409eff;
  font-weight: bold;
  margin-right: 8px;
}

.question-content {
  color: #303133;
}

.required-mark {
  color: #f56c6c;
  margin-left: 5px;
}

.question-options {
  margin-left: 20px;
}

.option-item {
  display: block;
  margin-bottom: 10px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.option-item:hover {
  background-color: #f5f7fa;
}

.question-text {
  margin-left: 20px;
}

.form-actions {
  text-align: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.form-actions .el-button {
  margin: 0 10px;
  min-width: 120px;
}
</style> 